package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmy.cultivate.entity.Course;
import com.xmy.cultivate.entity.CoursePricing;
import com.xmy.cultivate.entity.OrderApply;
import com.xmy.cultivate.entity.OrderDetail;
import com.xmy.cultivate.enums.OrderTypeEnum;
import com.xmy.cultivate.enums.ReadingStatusEnum;
import com.xmy.cultivate.enums.StatusOrderApplyEnum;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 * 订单报名信息 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2024-03-20
 */
@Service
public class OrderDetailServiceImpl extends ServiceImpl<OrderDetailMapper, OrderDetail> implements IOrderDetailService {

    @Autowired
    @Lazy
    IOrderApplyService iOrderApplyService;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    CourseMapper courseMapper;

    @Autowired
    @Lazy
    GradeMapper gradeMapper;

    @Autowired
    @Lazy
    StaffMapper staffMapper;

    @Autowired
    @Lazy
    OrganizationMapper organizationMapper;

    @Autowired
    @Lazy
    StudentMapper studentMapper;

    @Autowired
    @Lazy
    SubjectsMapper subjectsMapper;

    @Autowired
    @Lazy
    IStudentTypeService iStudentTypeService;

    @Autowired
    @Lazy
    StudentGradeMapper studentGradeMapper;

    @Autowired
    @Lazy
    EnrollInfoMapper enrollInfoMapper;

    @Autowired
    @Lazy
    IEnrollInfoService iEnrollInfoService;

    @Autowired
    @Lazy
    ICourseService iCourseService;

    @Autowired
    @Lazy
    ICoursePricingService iCoursePricingService;

    @Autowired
    @Lazy
    IOrderDisDetailService iOrderDisDetailService;

    @Autowired
    @Lazy
    IOrderApplyAffirmService iOrderApplyAffirmService;

    @Autowired
    @Lazy
    IdWorker idWorker;

    /**
     * 智能课自动报名
     * @return
     */
    @Override
    public boolean addOrderApply(Integer yearPart,Integer quarterNum,Long schoolId,Long subjectsId,Integer lessonType,Long studentId){


        List<OrderDetail> orderDetailList = this.getStudentOrderDetail(yearPart,quarterNum,schoolId,subjectsId,lessonType,studentId);

        LocalDate localDateNow = LocalDate.now();
        Integer i=1;
        for (OrderDetail orderDetail :orderDetailList){
            //System.out.println("count:"+orderDetailList.size()+"i:"+i);
            i++;
            OrderDetail orderDetailItem = null;
            Integer lessonTypeInsert = null;
            if (orderDetail.getSubjectsId().equals(1L)){
                lessonTypeInsert = 2;
            }else if (orderDetail.getSubjectsId().equals(2L) || orderDetail.getSubjectsId().equals(3L)){
                //类型刷题班
                lessonTypeInsert = 3;;
            }
            Integer residueCourseCount = orderDetail.getResidueCourseCount()*2;

            QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
            courseQueryWrapper.eq("lesson_type",lessonTypeInsert);
            courseQueryWrapper.eq("subjects_id",orderDetail.getSubjectsId());
            courseQueryWrapper.eq("status",1);
            courseQueryWrapper.eq("quarter_num",quarterNum);
            courseQueryWrapper.last("limit 1");
            //courseQueryWrapper.eq();

            Course course = iCourseService.getOne(courseQueryWrapper);
            if (course == null){
                continue;
            }
            QueryWrapper<CoursePricing> coursePricingQueryWrapper = new QueryWrapper<>();
            if(course.getOpeningSchoolType().getKey().equals(1)){
                coursePricingQueryWrapper.inSql("price_school_id","select id from course_price_school where course_id = "+course.getId()+" and school_id =0 and deleted=0");
            }else {
                coursePricingQueryWrapper.inSql("price_school_id","select id from course_price_school where course_id = "+course.getId()+" and school_id ="+orderDetail.getSchoolId()+" and deleted=0");

            }

            /*if((residueCourseCount%45) == 0){
                coursePricingQueryWrapper.eq("count",45);
            }else {
                coursePricingQueryWrapper.eq("count",3);
            }*/
            //coursePricingQueryWrapper.eq("status",1);
            coursePricingQueryWrapper.last("limit 1");


            CoursePricing coursePricing = iCoursePricingService.getOne(coursePricingQueryWrapper);
            if (coursePricing ==null){
                continue;
            }

            orderDetailItem = orderDetailMapper.getStudetnOrderDetailForLessonType(yearPart,quarterNum,orderDetail.getSchoolId(),orderDetail.getSubjectsId(),lessonTypeInsert,orderDetail.getStudentId());
            if (orderDetailItem == null){
                Integer randReceiptNo = CommonUtil.getReceiptNo(7);
                Long orderId = idWorker.nextId();
                StringBuilder tradeContent = new StringBuilder();
                tradeContent.append("报名：");
                tradeContent.append(course.getName());
                //tradeContent.append(",");
                //tradeContent.append(residueCourseCount);
                //tradeContent.append("课时");

                OrderApply orderApply = new OrderApply();
                orderApply.setId(orderId);
                orderApply.setReceiptNo(randReceiptNo.toString());
                orderApply.setLessonType(lessonTypeInsert);
                orderApply.setPrice(new BigDecimal(0));
                orderApply.setStudentId(orderDetail.getStudentId());
                orderApply.setSchoolId(orderDetail.getSchoolId());
                orderApply.setYearPart(yearPart);
                orderApply.setQuarterNum(quarterNum);
                orderApply.setHandleSchoolId(orderDetail.getSchoolId());
                //orderApply.setHandleSchoolName();
                orderApply.setHandleDate(localDateNow);
                //orderApply.setHandlePersonId();
                //orderApply.setHandlePersonName();
                orderApply.setStatus(StatusOrderApplyEnum.NO);
                orderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_SiGN);
                orderApply.setTradeContent(tradeContent.toString());
                orderApply.setCreatedId(orderDetail.getCreatedId());
                iOrderApplyService.save(orderApply);

                orderDetailItem = new OrderDetail();
                orderDetailItem.setResidueCourseCount(residueCourseCount);
                orderDetailItem.setId(idWorker.nextId());
                orderDetailItem.setOrderId(orderId);
                orderDetailItem.setSchoolId(orderDetail.getSchoolId());
                orderDetailItem.setStudentId(orderDetail.getStudentId());
                orderDetailItem.setLessonType(lessonTypeInsert);
                orderDetailItem.setCourseId(course.getId());
                orderDetailItem.setCourseName(course.getName());
                orderDetailItem.setSubjectsId(orderDetail.getSubjectsId());
                //orderDetailItem.setGradeId();
                orderDetailItem.setCoursePriceId(coursePricing.getId());
                orderDetailItem.setYearClassId(orderDetail.getYearClassId());
                //orderDetailItem.setCount(residueCourseCount/coursePricing.getCount());
                orderDetailItem.setAllCourseCount(residueCourseCount);
                //orderDetailItem.setUseCourseCount();
                orderDetailItem.setResidueCourseCount(residueCourseCount);
                //orderDetailItem.setCourseHouse();
                orderDetailItem.setUsePrice(new BigDecimal(0));
                orderDetailItem.setEnrollType(1);
                orderDetailItem.setHandleDate(localDateNow);
                orderDetailItem.setYearPart(yearPart);
                orderDetailItem.setQuarterNum(quarterNum);
                orderDetailItem.setYearAndQuarter(Integer.parseInt(yearPart+""+quarterNum));
                orderDetailItem.setOrderType(OrderTypeEnum.ORDER_TYPE_SiGN);
                orderDetailItem.setStatus(StatusOrderApplyEnum.NO);
                orderDetailItem.setReadingStatus(ReadingStatusEnum.IN_READING);
                orderDetailItem.setCreatedId(orderDetailItem.getCreatedId());

            }else {
                //BeanUtils.copyProperties(orderDetail,orderDetailItem);
                orderDetailItem.setResidueCourseCount(residueCourseCount);

            }
            this.saveOrUpdate(orderDetailItem);
        }
        return true;
    }

    /**
     * 获取剩余课时大于0的各科目数据
     * @param yearPart
     * @param quarterNum
     * @param schoolId
     * @param subjectsId
     * @param lessonType
     * @param studentId
     * @return
     */
    public List<OrderDetail> getStudentOrderDetail(Integer yearPart,Integer quarterNum,Long schoolId,Long subjectsId,Integer lessonType,Long studentId){
        return orderDetailMapper.getStudentOrderDetail(yearPart,quarterNum,schoolId,subjectsId,lessonType,studentId);
    }


    /**
     *
     * @param schoolId
     * @param studentId
     * @param subjectsId
     * @param yearPart
     * @param quarterNum
     * @param lessonType
     * @return
     */
    @Override
    public boolean updateResidueCourse(Integer yearPart, Integer quarterNum, Long schoolId, Long subjectsId, Integer lessonType, Long studentId){
        Integer yearAndQuarter = Integer.parseInt(yearPart+""+quarterNum);
        Integer residueCourse = orderDetailMapper.getResidueCourseCountForSubjects(schoolId,studentId,subjectsId,yearAndQuarter,lessonType);
        if (residueCourse.equals(0)){
            Integer residueCourseCount = 0;
            Integer lessonTypeUpdate = 0;
            if (subjectsId.equals(1L)){
                lessonTypeUpdate =2;
            }else if (subjectsId.equals(2L) || subjectsId.equals(3L)){
                lessonTypeUpdate = 3;
            }
            orderDetailMapper.updateResidueCourse(yearPart,quarterNum,schoolId,subjectsId,lessonTypeUpdate,studentId,residueCourseCount);
        }
        return true;
    }

    @Override
    public OrderDetail getCourseHouseAndPrice(Integer yearPart,
                                              Integer quarterNum,
                                              Long schoolId,
                                              Long subjectsId,
                                              Integer lessonType,
                                              Long studentId){
        OrderDetail orderDetail =  orderDetailMapper.getCourseHouseAndPrice(yearPart,quarterNum,schoolId,subjectsId,lessonType,studentId);
        return orderDetail;
    }
}
